package com.example.myapplication.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.DividerItemDecoration;

import com.example.myapplication.R;
import com.example.myapplication.adapter.RecordAdapter;
import com.example.myapplication.data.Record;
import com.example.myapplication.data.RecordRepository;
import com.example.myapplication.databinding.FragmentHomeBinding;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.widget.NumberPicker;
import android.util.Log;
import android.content.SharedPreferences;
import android.content.Context;

public class HomeFragment extends Fragment implements RecordAdapter.OnRecordActionListener {

    private static final String TAG = "HomeFragment";
    private FragmentHomeBinding binding;
    private RecordRepository repository;
    private RecordAdapter recordAdapter;
    private Calendar calendar;
    private SimpleDateFormat monthFormat;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        initializeComponents();
        setupRecyclerView();
        setupAddButton();
        observeRecords();

        return root;
    }

    private void initializeComponents() {
        repository = new RecordRepository(requireActivity().getApplication());
        calendar = Calendar.getInstance();
        monthFormat = new SimpleDateFormat("yyyy年MM月", Locale.getDefault());
        
        // 设置月份选择器点击事件
        binding.datePicker.setOnClickListener(v -> showMonthPicker());
        
        // 显示当前月份
        updateMonthDisplay();
    }

    private void setupRecyclerView() {
        recordAdapter = new RecordAdapter(new ArrayList<>(), this);
        binding.recordsList.setLayoutManager(new LinearLayoutManager(requireContext()));
        binding.recordsList.setAdapter(recordAdapter);
        binding.recordsList.addItemDecoration(new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL));
    }

    private void setupAddButton() {
        binding.addRecordButton.setOnClickListener(v ->
            Navigation.findNavController(v).navigate(R.id.action_navigation_home_to_addRecordFragment)
        );
    }

    private void observeRecords() {
        // 获取选中月份的开始和结束时间
        Calendar start = (Calendar) calendar.clone();
        start.set(Calendar.DAY_OF_MONTH, 1);
        start.set(Calendar.HOUR_OF_DAY, 0);
        start.set(Calendar.MINUTE, 0);
        start.set(Calendar.SECOND, 0);
        start.set(Calendar.MILLISECOND, 0);

        Calendar end = (Calendar) calendar.clone();
        end.set(Calendar.DAY_OF_MONTH, end.getActualMaximum(Calendar.DAY_OF_MONTH));
        end.set(Calendar.HOUR_OF_DAY, 23);
        end.set(Calendar.MINUTE, 59);
        end.set(Calendar.SECOND, 59);
        end.set(Calendar.MILLISECOND, 999);

        Log.d(TAG, "Observing records from " + start.getTime() + " to " + end.getTime());

        // 观察记录变化
        repository.getRecordsByDateRange(start.getTimeInMillis(), end.getTimeInMillis())
                .observe(getViewLifecycleOwner(), records -> {
                    Log.d(TAG, "Records updated: " + (records != null ? records.size() : 0) + " records");
                    if (records != null) {
                        recordAdapter.updateRecords(records);
                        updateSummary(records);
                    }
                });

        // 添加测试代码
        new Thread(() -> {
            List<Record> allRecords = repository.getAllRecordsDirectly();
            Log.d(TAG, "All records in database: " + allRecords.size());
            for (Record record : allRecords) {
                Log.d(TAG, "Record: " + record.toString());
            }
        }).start();
    }

    private void updateSummary(List<Record> records) {
        double totalExpense = 0;
        double totalIncome = 0;

        for (Record record : records) {
            if (record.isExpense()) {
                totalExpense += record.getAmount();
            } else {
                totalIncome += record.getAmount();
            }
        }

        binding.expenseAmount.setText(String.format("¥%.2f", totalExpense));
        binding.incomeAmount.setText(String.format("¥%.2f", totalIncome));
        binding.balanceAmount.setText(String.format("¥%.2f", totalIncome - totalExpense));
        
        // 从SharedPreferences获取预算并计算剩余预算
        SharedPreferences sharedPreferences = requireContext().getSharedPreferences(
                "EasyAccountPrefs", Context.MODE_PRIVATE);
        String budgetStr = sharedPreferences.getString("monthly_budget", "0");
        try {
            double budget = Double.parseDouble(budgetStr);
            double remainingBudget = budget - totalExpense;
            binding.budgetAmount.setText(String.format("¥%.2f", remainingBudget));
        } catch (NumberFormatException e) {
            binding.budgetAmount.setText("¥0.00");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onRecordEdit(Record record) {
        // 创建Bundle来传递记录数据
        Bundle args = new Bundle();
        args.putInt("recordId", record.getId());
        args.putBoolean("isExpense", record.isExpense());
        args.putString("category", record.getCategory());
        args.putFloat("amount", (float) record.getAmount());
        args.putLong("date", record.getDate());
        args.putString("note", record.getNote());

        // 导航到编辑页面
        NavController navController = Navigation.findNavController(requireView());
        navController.navigate(R.id.action_navigation_home_to_addRecordFragment, args);
    }

    @Override
    public void onRecordDelete(Record record) {
        repository.delete(record);
        Toast.makeText(requireContext(), "记录已删除", Toast.LENGTH_SHORT).show();
    }

    private void showMonthPicker() {
        View dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_month_picker, null);
        NumberPicker yearPicker = dialogView.findViewById(R.id.year_picker);
        NumberPicker monthPicker = dialogView.findViewById(R.id.month_picker);

        // 设置年份范围（前后5年）
        int currentYear = calendar.get(Calendar.YEAR);
        yearPicker.setMinValue(currentYear - 5);
        yearPicker.setMaxValue(currentYear + 5);
        yearPicker.setValue(calendar.get(Calendar.YEAR));

        // 设置月份范围（1-12）
        monthPicker.setMinValue(1);
        monthPicker.setMaxValue(12);
        monthPicker.setValue(calendar.get(Calendar.MONTH) + 1);

        new AlertDialog.Builder(requireContext())
                .setTitle("选择月份")
                .setView(dialogView)
                .setPositiveButton("确定", (dialog, which) -> {
                    calendar.set(Calendar.YEAR, yearPicker.getValue());
                    calendar.set(Calendar.MONTH, monthPicker.getValue() - 1);
                    updateMonthDisplay();
                    observeRecords(); // 重新加载选中月份的记录
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void updateMonthDisplay() {
        binding.datePicker.setText(monthFormat.format(calendar.getTime()));
    }
}